package com.example.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.model.Song;
import com.example.utils.JsonUtils;
import com.example.utils.RedisOperator;
import com.example.utils.ResultVOUtil;

@RestController
@RequestMapping("redis")
public class RedisController {

	@Autowired
	private StringRedisTemplate strRedis;

	@Autowired
	private RedisOperator redis;

	@GetMapping("/test")
	public Object test() {
		strRedis.opsForValue().set("hello", "fanjun");
		return ResultVOUtil.success(strRedis.opsForValue().get("hello"));
	}

	@GetMapping("/test2")
	public Object test2() {

		Song song = new Song();
		song.setName("夜曲");
		song.setSinger("周杰伦");
		song.setCreatetime(new Date().getTime());
		song.setUpdatetime(new Date().getTime());

		strRedis.opsForValue().set("json:song", JsonUtils.objectToJson(song));
		Song jsonSong = JsonUtils.jsonToPojo(strRedis.opsForValue().get("json:song"), Song.class);

		return ResultVOUtil.success(jsonSong);
	}

	@GetMapping("/test3")
	public Object test3() {

		Song song = new Song();
		song.setName("龙拳");
		song.setSinger("周杰伦");
		song.setCreatetime(new Date().getTime());
		song.setUpdatetime(new Date().getTime());

		Song song2 = new Song();
		song2.setName("醉赤壁");
		song2.setSinger("林俊杰");
		song2.setCreatetime(new Date().getTime());
		song2.setUpdatetime(new Date().getTime());

		Song song3 = new Song();
		song3.setName("美人鱼");
		song3.setSinger("林俊杰");
		song3.setCreatetime(new Date().getTime());
		song3.setUpdatetime(new Date().getTime());

		List<Song> songList = new ArrayList<>();
		songList.add(song);
		songList.add(song2);
		songList.add(song3);

		redis.set("json:info:songList", JsonUtils.objectToJson(songList), 2000);

		String songListJson = redis.get("json:info:songList");
		List<Song> songListBorn = JsonUtils.jsonToList(songListJson, Song.class);

		return ResultVOUtil.success(songListBorn);
	}

}
